package com.suxin.plugin.intergration.manager.loader;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author Tang
 * @classname PluginClassLoader
 * @description [  ]
 * @date 2022/7/3 21:42
 */
@Slf4j
public class PluginClassLoader extends URLClassLoader {

    private boolean parentFirst;

    public PluginClassLoader(ClassLoader parent) {
        this(new URL[0],parent,false);
    }

    public PluginClassLoader(URL[] urls, ClassLoader parent,boolean parentFirst) {
        super(urls, parent);
        this.parentFirst = parentFirst;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (!parentFirst) {
            try {
                return findClass(name);
            } catch (Exception e) {

            }
        }
        return super.loadClass(name);
    }

    protected void addFile(File file) {
        URL url = null;
        try {
            url = file.toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        super.addURL(url);
    }

    @Override
    protected void addURL(URL url) {
        log.debug("add '{}'",url);
        super.addURL(url);
    }
}